<template>
  <div class="dashboard-container">
    <div class="container">
      <!-- 搜索栏 -->
      <div class="tableBar">
        <el-form :inline="true" @submit.prevent="handleSearch">
          <el-form-item label="分类名称：">
            <el-input v-model="searchForm.name" placeholder="请填写分类名称" clearable @clear="handleSearch" />
          </el-form-item>
          <el-form-item label="分类类型：">
            <el-select v-model="searchForm.type" placeholder="请选择" clearable>
              <el-option label="菜品分类" :value="1" />
              <el-option label="套餐分类" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="search-btn" @click="handleSearch" :loading="loading">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="tableLab">
          <el-button type="primary" @click="openAddOrEditDialog('dish')">+ 新增菜品分类</el-button>
          <el-button type="warning" @click="openAddOrEditDialog('setmeal')">+ 新增套餐分类</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" stripe class="tableBox">
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="type" label="分类类型">
          <template #default="{ row }">
            <span>{{ row.type === 1 ? '菜品分类' : '套餐分类' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <div class="tableColumn-status" :class="{ 'stop-use': row.status === 0 }">
              <span :class="row.status === 1 ? 'status-dot-enabled' : 'status-dot-disabled'"></span>
              {{ row.status === 0 ? '禁用' : '启用' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="操作时间" min-width="150" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" class="blueBug" @click="openAddOrEditDialog(row)">修改</el-button>
            <el-button type="text" size="small" class="delBut" @click="handleDelete(row.id)">删除</el-button>
            <el-button type="text" size="small" :class="row.status === 0 ? 'blueBug' : 'delBut'"
              @click="handleStatusChange(row)">
              {{ row.status === 0 ? '启用' : '禁用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination v-if="total > 0" class="pageList" background layout="total, sizes, prev, pager, next, jumper"
        :total="total" v-model:current-page="page" v-model:page-size="pageSize" @current-change="fetchData"
        @size-change="fetchData" />
    </div>

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="分类名称：" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button v-if="dialog.action === 'add'" type="warning" @click="submitForm('continue')">保存并继续添加</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCategoryPage, deleteCategory, editCategory, addCategory, updateCategoryStatus } from '@/api/category';
import type { ICategory, ICategoryPageQuery } from '@/types/category';
import Empty from '@/components/Empty/index.vue';

// --- State ---
const router = useRouter();
const loading = ref(false);
const searchForm = reactive({ name: '', type: undefined });
const tableData = ref<ICategory[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);

const formRef = ref<FormInstance>();
const formData = reactive({ id: undefined, name: '', sort: '', type: 1 });
const dialog = reactive({
  title: '',
  visible: false,
  action: 'add' as 'add' | 'edit'
});

// --- Form Validation ---
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
});

// --- Core Methods ---
const fetchData = async () => {
  loading.value = true;
  try {
    const params: ICategoryPageQuery = {
      page: page.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      type: searchForm.type,
    };
    const response = await getCategoryPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } finally {
    loading.value = false;
  }
};
const handleSearch = () => {
  page.value = 1;
  fetchData();
};

// --- Actions ---
const openAddOrEditDialog = (typeOrData: 'dish' | 'setmeal' | ICategory) => {
  if (typeof typeOrData === 'string') { // 新增
    dialog.action = 'add';
    dialog.title = typeOrData === 'dish' ? '新增菜品分类' : '新增套餐分类';
    formData.type = typeOrData === 'dish' ? 1 : 2;
    formData.id = undefined;
    formData.name = '';
    formData.sort = '';
  } else { // 修改
    dialog.action = 'edit';
    dialog.title = '修改分类';
    formData.id = typeOrData.id;
    formData.name = typeOrData.name;
    formData.sort = String(typeOrData.sort);
    formData.type = typeOrData.type;
  }
  dialog.visible = true;
};

const submitForm = (mode?: 'continue') => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const apiCall = dialog.action === 'add' ? addCategory : editCategory;
      await apiCall(formData);
      ElMessage.success(`${dialog.action === 'add' ? '新增' : '修改'}成功！`);

      if (mode === 'continue') {
        formRef.value?.resetFields();
      } else {
        dialog.visible = false;
      }
      fetchData();
    }
  });
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm('此操作将永久删除该分类，是否继续？', '提示', { type: 'warning' }).then(async () => {
    await deleteCategory(id);
    ElMessage.success('删除成功！');
    fetchData();
  });
};

const handleStatusChange = (row: ICategory) => {
  const newStatus = row.status === 0 ? 1 : 0;
  ElMessageBox.confirm('确认调整该分类的状态?', '提示', { type: 'warning' }).then(async () => {
    await updateCategoryStatus({ id: row.id, status: newStatus });
    ElMessage.success('分类状态更改成功！');
    fetchData();
  });
};

// --- Lifecycle Hook ---
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
}

.container {
  background: #fff;
  padding: 30px 28px;
  border-radius: 4px;
}

.tableBar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.tableLab {
  display: flex;
  align-items: center;
}

.tableBox {
  width: 100%;
}

.pageList {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.search-btn {
  background-color: #333;
  color: white;
}

.tableColumn-status {
  display: flex;
  align-items: center;

  .status-dot-enabled {
    width: 8px;
    height: 8px;
    background-color: #67c23a;
    border-radius: 50%;
    margin-right: 5px;
  }

  .status-dot-disabled {
    width: 8px;
    height: 8px;
    background-color: #f56c6c;
    border-radius: 50%;
    margin-right: 5px;
  }

  &.stop-use {
    color: #f56c6c;
  }
}

.blueBug {
  color: #3370ff;
}

.delBut {
  color: #f56c6c;
}
</style>
